Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Is `if (idx < arr.length)` equivalent to `if (arr[idx])`?

Assuming that all elements inside an array have a value different from undefined, null or 0, is

if (idx < arr.length) equivalent to if (arr[idx])?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No.

There are other falsy values that will evaluate to false in the if statement, such as an empty string (''):

const arrWithEmptyString = ['', '', ''];
const idx = 2;

console.log(!!(idx < arrWithEmptyString.length));
console.log(!!arrWithEmptyString[idx]);

Alternatively, what if the array contains a boolean false?

const boolArray = [true, false, true, false]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);

Type coercion/type conversion in JS can be confusing and unpredictable-- in my opinion it is generally better to be explicit and test exactly what it is you mean to test, rather than relying on weak type comparisons to save a few characters.

about 4 years ago · Juan Pablo Isaza Report

0

Nice answer from Alexander Nied, also NaN evaluates to false

const boolArray = [NaN, NaN, NaN, NaN]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!